<?php

namespace IDock\Insurance\ZYIC\Response;

use IDock\Http\Request;
use IDock\Http\Response;

class AllZYICResponse extends Response
{

    public function resolve(): Response
    {
        $body = $this->getBody();
        if (!json_decode($body)) {
            $this->setError('返回数据异常');
            return  $this;
        }
        $data = json_decode($body,true);

        if ($this->printer and  is_string($this->printer)) {
            $this->printer = new $this->printer;
        }

        $resultCode = $data['code'] ?? '';
        $resultMess = $data['message'] ?? '';

        if($resultCode != '0000') {
            $this->setError($resultMess);
            return $this;
        }
        $this->setBody($data);

        return $this;
    }

    public function formatArray(array $arr)
    {
        if(empty($arr)) return $arr;
        if(!isset($arr[0])){
            $tmp = $arr;
            unset($arr);
            $arr[] = $tmp;
        }
        return $arr;
    }

    public function decrypt($key,Request $request)
    {
        $data = $this->getBody();
        if(!empty($data['data'])){
            $privateKey = openssl_get_privatekey($key);
            $out = '';
            foreach (str_split(base64_decode($data['data']),128) as $val){
                openssl_private_decrypt($val,$encrypted,$privateKey);
                $out .= $encrypted;
            }
            if(empty($out)){
                $this->setError( '解密失败');
                return  $this;
            }
            $out = str_replace(["\r\n","\n"],['',''],$out);
            $request->decryptLogs($request->getRequestId(),$out);
            $this->setBody(json_decode($out,true));
        }

        return $this;
    }
}
